<template>
  <Box class="traffic-warning-detail-wrapper" :title="title" direction="row" >
    <!-- 视频 -->
    <Panel second class="block video" align="center" :title="activeVideo.name">
      <VideoPlayer :url="activeVideo.url"></VideoPlayer>
    </Panel>

    <!--断面流量  -->
    <Panel second class="block" title="断面流量">
      <div class="count-same">
        <div class="count-box">
          <span class="count number">{{ flowState.flowCount || 0 }}</span> <span class="company">辆</span>
        </div>
        <!-- <SequentialSame class="same" :data="{ ring: flowState.flowRingRatio, same: flowState.flowWithRatio }">
        </SequentialSame> -->
      </div>
      <div class="spin-wrapper" v-if="chartLoading">
        <a-spin></a-spin>
      </div>
      <DashedLine renderType="拥堵预测" :xDate="xDate" v-else :seriesData="flowState.seriesData"></DashedLine>
    </Panel>

    <!-- 断面车速 -->
    <Panel second class="block" title="断面车速">
      <div class="count-same">
        <div class="count-box">
          <span class="count number">{{ speedState.speed || 0 }}</span> <span class="company">km/h</span>
        </div>
        <!-- <SequentialSame class="same" :data="{ ring: speedState.speedRingRatio, same: speedState.speedWithRatio }">
        </SequentialSame> -->
      </div>
      <div class="spin-wrapper" v-if="chartLoading">
        <a-spin></a-spin>
      </div>
      <DashedLine :xDate="xDate" renderType="拥堵预测" v-else :seriesData="speedState.seriesData"></DashedLine>
    </Panel>
  </Box>
</template>

<script>
/**
 * @desc 拥堵预测详情
 * @date 2022/10/22
 * @autheor  邓清波
 * **/
export default {
  name: 'TrafficWarningDetail'
}
</script>
<script setup>
import VideoPlayer from '@/components/video-player/VideoPlayer'
import DashedLine from '../../components/charts/DashedLine.vue'
import Panel from '../../components/panel'
import Box from '../../components/detail/Box.vue'
// import SequentialSame from '../../components/sequential-same'
import trafficApi from '../../api/traffic'
import baseServiceApi from '../../api/base-service'
import { ref, defineProps, watch, shallowRef, getCurrentInstance, computed } from 'vue'
import useMapOperates from '@/hooks/useMapOperates'
import { message } from 'ant-design-vue'
import { useStore } from 'vuex'
import useComputedDistanceRow from '@/hooks/useComputedDistanceRow'

const handleDark = useMapOperates()
const { proxy } = getCurrentInstance()
const store = useStore()
const roadType = computed(() => store.state.config.roadType)

const props = defineProps({
  data: {
    type: Object,
    default: () => ({})
  }
})

// 断面车速
const speedState = ref({
  speed: 0
})

// 断面流量
const flowState = ref({
  flowCount: 0,
  seriesData: []
})
const xDate = ref([]) // 图表时间线

// 摄像头名称、url
const activeVideo = ref({})

const title = shallowRef('')
const chartLoading = ref(false)

watch(
  () => props.data,
  newValue => {
    speedState.value = { speed: 0 }
    flowState.value = {
      flowCount: 0,
      seriesData: []
    }
    title.value = newValue.text
    getPointLine(newValue)
    getData()
  },
  {
    deep: true,
    immediate: true
  }
)

/**
 * 获取断面流量与车速
 */
function getData() {
  chartLoading.value = true
  const params = {
    gczbs: props.data.jamId,
    xsfx: props.data.roadDirection
  }
  trafficApi
    .getForecastSpeedFlow(params)
    .then(res => {
      if (res.data) {
        const data = res.data || {}
        xDate.value = data.timeList || []
        const {
          observationsFlow,
          forecastCapFlow,
          forecastLowFlow,
          observationsSpeed,
          forecastCapSpeed,
          forecastLowSpeed,
          speed,
          flowCount
        } = data
        speedState.value.speed = speed
        flowState.value.flowCount = flowCount

        speedState.value.seriesData = [
          {
            color: '#fe3636',
            name: '预测上限',
            data: forecastCapSpeed || []
          },
          {
            color: '#16ade1',
            name: '预测下限',
            data: forecastLowSpeed || []
          },
          {
            color: '#4fce8e',
            name: '观测数值',
            data: observationsSpeed || []
          }
        ]
        flowState.value.seriesData = [
          {
            color: '#fe3636',
            name: '预测上限',
            data: forecastCapFlow || []
          },
          {
            color: '#16ade1',
            name: '预测下限',
            data: forecastLowFlow || []
          },
          {
            color: '#4fce8e',
            name: '观测数值',
            data: observationsFlow || []
          }
        ]
      }
    })
    .finally(() => {
      chartLoading.value = false
    })
}

/**
 * 打点、画线
 */
function getPointLine(newValue) {
  if (newValue.lon && newValue.lat) {
    proxy.$mapSdk().setMvMapCenterAndZoom([Number(newValue.lon), Number(newValue.lat)], 13)
    handleDark('marker', [
      {
        icon: 'zhdd-gl-jdd-active',
        path: [newValue.lon, newValue.lat],
        name: newValue.text,
        zIndex: 105,
        size: [30, 35],
        offset: [-15, -35]
      }
    ])
  }
  if (!newValue.roadNum) return message.warning('路段编号缺失')
  const params = {
    roadNum: newValue.roadNum, //  string 是 示例值：G2说明：路段编号
    startStake: newValue.startStakeKm + '.' + newValue.startStakeM, //  number 是 示例值：450说明：开始桩号
    endStake: newValue.endStakeKm + '.' + newValue.endStakeM //  number 是 示例值：1000说明：结束桩号
  }
  // 获取路线
  getLineLatLonList(newValue, params)
  // 获取摄像机
  params.resourceType = 6
  getBaseInfo(params)
}

/** *
 * @desc  获取路线
 * @param params  请求参数
 *
 ***/
function getLineLatLonList(newValue, params) {
  baseServiceApi.getLineLatLonList(params).then(res => {
    if (res.data && res.data.length) {
      const path = res.data[0].lonLat.split(';').map(i => i.split(','))
      const lines = [
        {
          name: newValue.text,
          path,
          config: {
            lineWidth: 8,
            lineColor: newValue.lineColor || '',
            selectWidth: 10,
            selectColor: newValue.lineColor || ''
          }
        }
      ]
      handleDark('polyline', lines)
    }
  })
}

/** *
 * @desc  获取摄像机、情报板并打点
 * @param params  请求参数
 * @param type    类型  6摄像机、7情报板
 *
 ***/
function getBaseInfo(params, type = 'sxj') {
  baseServiceApi
    .getBaseInfoList(params)
    .then(res => {
      if (res.data && res.data.length) {
        res.data = res.data.map((item, index) => {
          const newObj = {
            ...item,
            id: item.resourcesId,
            cameraId: item.resourcesId,
            roadType: roadType.value,
            icon: 'zhdd-gl-' + type,
            path: [item.lng, item.lat],
            name: item.resourcesName,
            hasClickStatus: true,
            size: [30, 35],
            offset: [-15, -35]
          }

          return newObj
        })
        const result = useComputedDistanceRow([props.data.lon, props.data.lat], res.data)
        console.log('result', result)
        if (result && result.length) {
          result[0].icon = 'zhdd-gl-' + type + '-active'
          getVideoUrl(result[0])
          handleDark('marker', [result[0]])
          result.splice(0, 1)
        }

        handleDark('marker', result, { type })
      }
    })
    .catch(e => {
      console.log('err', e)
    })
}

/** *
 * @desc  获取摄像机url
 * @param data  数据对象
 *
 **/
function getVideoUrl(data) {
  const params = {
    cameraId: data.cameraId,
    roadType: data.roadType,
    videoType: 1
  }
  baseServiceApi.getCameraUrl(params).then(res => {
    if (res.detail) {
      activeVideo.value = {
        ...data,
        url: res.detail
      }
    }
  })
}
</script>

<style scoped lang="less">
@import url(../../styles/themes/index.less);
.block {
  flex: 1;

  .spin-wrapper {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .chart-title {
    font-size: 14px;
    color: #333333;
  }

  .count-same {
    display: flex;
    width: 100%;
    justify-content: space-between;

    .count-box {
      .count {
        line-height: 32px;
        font-size: 32px;
        text-align: left;
        color: #266bf4;
      }
    }

    .same {
      width: 180px;
      padding-right: 5px;
    }
  }
}

.video {
  flex: none !important;
  width: 30%;
}
</style>
